package com.train.fibonacci.generate;

import java.util.ArrayList;
import java.util.List;

import com.train.fibonacci.report.FibonacciReporter;

public class DynamicRecursiveFibonacciGenerator implements FibonacciGenerator {

	private List<Long> fibonacciList = new ArrayList<>();
	
	@Override
	public void generate(int length, FibonacciReporter reportor) {
		if (length < 0) {
			throw new IllegalArgumentException();
		}
		
		for (int i = 0; i < length; i++) {
			long num = calculate(i);
			reportor.report(num);
		}
	}
	
	private long calculate(int index) {
		System.out.println("Log: calculate dynamic Fibonacci index: " + index);
		if (index == 0) {
			if (fibonacciList.size() < 1) {
				fibonacciList.add(A);
			}
		} else if (index == 1) {
			if (fibonacciList.size() < 2) {
				calculate(0);
				fibonacciList.add(B);
			}
		} else {
			if (fibonacciList.size() < index + 1) {
				long a = calculate(index - 2);
				long b = calculate(index - 1);
				fibonacciList.add(a + b);
			}
		}
		return fibonacciList.get(index);
	}
}
